package com.caiyi.financial.nirvana.sms.gateway.http;

import com.alibaba.fastjson.JSON;
import com.caiyi.financial.nirvana.sms.enums.SmsMsgStatusEnum;
import com.caiyi.financial.nirvana.sms.queue.NotifyQueueEntity;
import com.caiyi.financial.nirvana.sms.queue.ReceiveMsgQueueEntity;
import com.caiyi.financial.nirvana.sms.queue.SendQueueEntity;
import com.caiyi.financial.nirvana.sms.util.MD5Util;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class LianJiangGateway extends BaseGateway {

    private static final Logger logger = LoggerFactory.getLogger(LianJiangGateway.class);
    private static final int SUCCESS_CODE = 20000;
    private static final String QUERY_REPORT_URL = "http://api.ljioe.cn/api/v1/report";
    private static final String QUERY_BALANCE_URL = "http://api.ljioe.cn/api/v1/accountNum";

    @Override
    public void sendMessage(SendQueueEntity entity) {
        int status = SmsMsgStatusEnum.REQUEST_FAIL.index;
        String result = "";
        try {
            String params = buildParams(entity);
            String response = doPost(info.getServerAddr(), params);
            logger.info("LianJiangGateway sendMessage url : {}, params : {}, result : {}", info.getServerAddr(), params, response);
            Map resultMap = JSON.parseObject(response, Map.class);
            if (SUCCESS_CODE == Integer.parseInt(resultMap.get("code").toString())) {
                status = SmsMsgStatusEnum.REQUEST_SUCCESS.index;
                result = resultMap.get("msgId").toString();
            } else {
                result = resultMap.get("code") + resultMap.get("desc").toString();
            }
        } catch (Exception e) {
            logger.error("LianJiangGateway sendMessage error ! ", e);
        } finally {
            onSubmitResponse(status, entity.getMessageId(), result);
        }
    }

    private String buildParams(SendQueueEntity entity) {
        long timestamp = System.currentTimeMillis() / 1000;
        Map params = new HashMap();
        params.put("account", info.getAccount());
        params.put("timestamp", timestamp);
        params.put("ext", entity.getMessageId());
        params.put("code", entity.getAccessNumber());
        params.put("mobile", entity.getPhone());
        params.put("content", entity.getContent());
        params.put("key", MD5Util.encode(info.getPassword() + MD5Util.encode(timestamp + "").toLowerCase()).toLowerCase());
        return JSON.toJSONString(params);
    }

    @Override
    public boolean notifyStatus(NotifyQueueEntity entity) {
        return false;
    }

    @Override
    public int queryBalance() throws Exception {
        long timestamp = System.currentTimeMillis() / 1000;
        Map params = new HashMap();
        params.put("account", info.getAccount());
        params.put("timestamp", timestamp);
        params.put("key", MD5Util.encode(info.getPassword() + MD5Util.encode(timestamp + "").toLowerCase()).toLowerCase());
        String paramsStr = JSON.toJSONString(params);
        String response = doPost(QUERY_BALANCE_URL, paramsStr);
        logger.info("LianJiangGateway queryBalance url : {}, params : {}, result : {}", QUERY_BALANCE_URL, params, response);
        Map resultMap = JSON.parseObject(response, Map.class);
        if (SUCCESS_CODE == Integer.parseInt(resultMap.get("code").toString())) {
            return Integer.parseInt(resultMap.get("smsNum").toString());
        }
        return 0;
    }

    @Override
    public boolean queryStatus() throws Exception {
        long timestamp = System.currentTimeMillis() / 1000;
        Map params = new HashMap();
        params.put("account", info.getAccount());
        params.put("timestamp", timestamp);
        params.put("key", MD5Util.encode(info.getPassword() + MD5Util.encode(timestamp + "").toLowerCase()).toLowerCase());
        String paramsStr = JSON.toJSONString(params);
        String response = doPost(QUERY_REPORT_URL, paramsStr);
        logger.info("LianJiangGateway queryStatus url : {}, params : {}, result : {}", QUERY_REPORT_URL, paramsStr, response);
        Map resultMap = JSON.parseObject(response, Map.class);
        if (SUCCESS_CODE == Integer.parseInt(resultMap.get("code").toString())) {
            List<Map> list = (List<Map>) resultMap.get("list");
            for (Map map : list) {
                int status = SmsMsgStatusEnum.SEND_FAIL.index;
                String messageId = map.get("ext") + "";
                String code = map.get("code") + "";
                if ("DELIVERED".equals(code) || "DELIVRD".equals(code)) {
                    status = SmsMsgStatusEnum.SEND_SUCCESS.index;
                }
                String result = map.get("code") + "" + map.get("msgId");
                receiveReport(status, messageId, result);
            }
        }
        return false;
    }

    @Override
    public boolean receiveMsg(ReceiveMsgQueueEntity entity) {
        return false;
    }
}

